<template>
  <div class="chart-box">
    <div class="friends-area">
      <div class="profile">userName</div>
      <div>
        <button @click="queryFriendDialogVisible = true">add friends</button>
        <button @click="openFriendListAndQuery">newFirendList</button>
      </div>
      <div class="friend-item" v-for="item in friendList" @click="changeCurrentTalkingFriend(item.userName)">{{ item.userName }}</div>
    </div>
    <div class="chart-area">
      <div>titlesds</div>
      <div ref="chartContent" class="chart-content">
        <div>old</div>
        <chartItem v-for="item in currentCharts" :side="chartLeftOrRight(localUser.getUser().userName,item.from)" :message="item.content" type=""></chartItem>
      </div>
      <div class="sendding-area">
        <input v-model="message" @keypress="sentMessage" />
        <!-- <button @click="add(message)">ad</button> -->
      </div>
    </div>
  </div>

  <!-- ##############################queryFriendDialogVisible############################# -->
  <el-dialog
    v-model="queryFriendDialogVisible"
    title="FIND SOME NEW FRIENDS"
    width="60%"
  >
  <div>
    <div>
      <el-input v-model="friendName"  style="width: 200px" placeholder="Please input your new Friend's name" />
      <button @click="findFriendsByName">find!</button>
    </div>
    <div class="newfriendarea">
      <friendCard v-for="item in newFriendRes" :name="item.name" @addfriend="addNewFriend"></friendCard>
    </div>
  </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="queryFriendDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="queryFriendDialogVisible = false">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- ##########################queryFriendDialogVisible########################### -->
    <!-- ##############################newFriendListDialogVisible############################# -->
    <el-dialog
    v-model="newFriendListDialogVisible"
    title="NEW FRIEND APPLY"
    width="60%"
  >
  <div>
    <div class="newfriendarea">
      <newFriendApplyCard v-for="item in nreFriendApplyList" :name="item.userName" @confirm="confirmNewFriendApply"></newFriendApplyCard>
    </div>
  </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="newFriendListDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="newFriendListDialogVisible = false">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- ##########################newFriendListDialogVisible########################### -->
</template>
<script setup lang="ts">
import {ref,onMounted,watch} from 'vue'
import chartItem from '@/components/chartItem.vue';
import {findFriendsByNameApi ,addFirednApi, getFriendApplyListApi, confirmNewFriendApplyApi,getAllfriendsApi, getChartRecordApi} from '@/api/userAPi'
import {loginWs} from '@/api/ws/ws'
import friendCard from '@/components/friendCard.vue';
import newFriendApplyCard from '@/components/newFriendApplyCard.vue'
import { useLocalUserStore } from '@/stores/localUser';
import FriendCard from '@/components/friendCard.vue';
import {WS_REQ_CHART, type ChartRecord, type WsReq, type WsRes} from '@/types'
import { handleWsRes, chartLeftOrRight } from '@/utils';

const currentTalkintFriend = ref('')
const friendList = ref<Array<any>>([])
const localUser = useLocalUserStore()
const queryFriendDialogVisible = ref(false)
const newFriendListDialogVisible = ref(false)
const friendName = ref('')
const chartContent = ref<HTMLDivElement>()
const left = false;
const right = true;
const conut = ref(0)
const newFriendRes = ref<Array<any>>([])
const nreFriendApplyList = ref<Array<any>>()
const currentCharts = ref<Array<ChartRecord>>([])

getAllfriendsApi(localUser.getUser().userName).then(res => {
    friendList.value = res.data.friends
    if(friendList.value.length != 0) {
      currentTalkintFriend.value = friendList.value[0].userName
      console.log("first fetch the chart record.");
      getChartRecordApi(localUser.getUser().userName,currentTalkintFriend.value).then(res => {
        currentCharts.value = res.data.records
      })
      
    }

})
type Message = {
  side:boolean,
  message:string,
  type:string,
  time:string
}

const message = ref('')
//todo!!!该参数。
const add = (msg:string,from:string,to:string) => {
  currentCharts.value?.push(
    {
      from:from,
      to:to,
      content:msg,
      date:'now'
    }
  )
  conut.value++
  const divEL = chartContent.value as HTMLDivElement
  setTimeout(() => {
    divEL.scrollTop = divEL.scrollHeight as number
  }, 10);
}

const ws = loginWs(localUser.getUser().userName)
ws.onopen = () => {
  console.log("ws open");
}
ws.onerror = (e)=> {
  console.log(e);
}
ws.onmessage = (e) => {
  const data:WsRes = JSON.parse(e.data)
  handleWsRes(data,currentCharts,add)
}
ws.onclose = (e) => {
  console.log(e);
}
const changeCurrentTalkingFriend = (friendName:string) => {
  //TODO fetch  chart record
  if(currentTalkintFriend.value != friendName) {
    console.log("fetch && curren friend is " + friendName);
    currentTalkintFriend.value = friendName
    console.log("fetch" + friendName);
    getChartRecordApi(localUser.getUser().userName,currentTalkintFriend.value).then(res => {
        currentCharts.value = res.data.records
      })
  }
  
}
const openFriendListAndQuery = () => {
  newFriendListDialogVisible.value = true
  getFriendApplyListApi(localUser.getUser().userName).then(res => {
    nreFriendApplyList.value = res.data.users
  })
}
const addNewFriend = (friendName:string) => {
  addFirednApi(localUser.getUser().userName,friendName)
}
const sentMessage = (e:KeyboardEvent) => {
  if(e.key == 'Enter') {
    add(message.value,localUser.getUser().userName,currentTalkintFriend.value)

    const from = localUser.getUser().userName
    const to = currentTalkintFriend.value
    const content = message.value
    message.value = ''
    const wsReq:WsReq = {
      type:WS_REQ_CHART,
      content:{
        from,
        to,
        content
      }
    }
    
    ws.send(JSON.stringify(wsReq))
  }
}
const findFriendsByName = () => {
  findFriendsByNameApi(friendName.value).then(res => {
    newFriendRes.value = res.data.users
  })
}
const confirmNewFriendApply = (friendName:string) => {
  console.log(friendName);
  confirmNewFriendApplyApi(localUser.getUser().userName,friendName)
}
</script>

<style scoped>
.chart-box {
  margin: 0 auto;
  width:1000px;
  border: 1px solid #CCC;
  height: 99%;
  display: flex;
  flex-direction: row;
}
.friends-area {
  height: 100%;
  flex: 1;
  border-right: 1px solid #CCC;
  overflow: auto;
}
.chart-area {
  flex: 3;
  display: flex;
  flex-direction: column;
}
.profile {
  height: 100px;
  background-color: aliceblue;
}
.chart-content {
  flex: 6;
  background-color: antiquewhite;
  overflow: auto;
}
.sendding-area {
  flex: 2;
}
.newfriendarea {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
}
.friend-item {
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  transition: all ease 0.4s;
}
.friend-item:hover {
  background-color: bisque;
}
</style>
